<?php

namespace app\api\controller;

use app\api\job\CircleJob;
use app\api\lib\SuPengJun;
use app\common\model\dynamic\DynamicCommentModel;
use app\common\model\dynamic\DynamicImgModel;
use app\common\model\dynamic\DynamicLikeModel;
use app\common\model\dynamic\DynamicModel;
use app\common\model\dynamic\DynamicVideoModel;
use app\common\model\NoticeModel;
use app\common\model\user\UserModel;
use app\api\service\DynamicService;
use app\common\model\dynamic\DynamicAudioModel;
use app\common\model\order\OrderGoodsModel;
use app\common\model\order\OrderModel;
use app\common\model\user\UserFollowModel;
use dengje\workerman\process\queue\Client;
use think\facade\Db;
use think\Request;

class Dynamic extends Controller
{
    protected array $middleware = [
        'api' => ['except' => ['recommend', 'details']],
        'orCheck' => ['only' => ['recommend', 'details']]
    ];

    /**
     * 发布动态、保存草稿箱
     * @param array $params['id'] 动态ID，存在时为编辑，不存在时为新增
     * @param array $params['content'] 动态文本内容
     * @param array $params['type'] 动态类型：1=图文 2=视频 3=音频
     * @param array $params['status'] 发布状态：0=草稿 1=发布
     * @param array $params['order_type'] 订单类型（不明确作用）
     * @param array $params['order_id'] 关联订单ID
     * @param array $params['goods'] 商品数据数组（小程序端未发现添加商品的地方）
     * @param array $params['circle']['id'] 圈子ID
     * @param array $params['circle']['name'] 圈子名称
     * @param array $params['circle']['avatar'] 圈子头像
     * @param array $params['activity']['id'] 活动ID
     * @param array $params['activity']['name'] 活动名称
     * @param array $params['activity']['img'] 活动图片
     * @param array $params['adds']['address'] 位置地址
     * @param array $params['adds']['name'] 位置名称
     * @param array $params['adds']['latitude'] 纬度
     * @param array $params['adds']['longitude'] 经度
     * @param array $params['imgs'] 图片数组（type=1时必填）
     * @param array $params['imgs'][]['url'] 图片URL
     * @param array $params['imgs'][]['wide'] 图片宽度
     * @param array $params['imgs'][]['high'] 图片高度
     * @param array $params['video'] 视频数据（type=2时必填）
     * @param array $params['video']['url'] 视频URL
     * @param array $params['video']['cover'] 视频封面
     * @param array $params['video']['wide'] 视频宽度
     * @param array $params['video']['high'] 视频高度
     * @param array $params['audio'] 音频数据（type=3时必填）
     * @param array $params['audio']['url'] 音频URL
     * @param array $params['audio']['cover'] 音频封面
     * @param array $params['audio']['name'] 音频名称
     * @param array $params['audio']['intro'] 音频简介
     * @param array $params['audio']['size'] 音频大小
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function save(Request $request)
    {
        $uid = $request->uid;
        if (UserModel::where('id', $uid)->value('status') == 0) return error('当前账号已被禁言！');
        $params = $request->post();
        if ($params['order_type'] == 9) {
            OrderModel::where('id', $params['order_id'])->delete();
            OrderGoodsModel::where('order_id', $params['order_id'])->delete();
            $params['order_id'] = '';
        }
        if (!$params['order_id'] && !empty($params['goods'])) {
            $params['order_id'] = (new OrderModel())->insertGetId([
                'order_no' => SuPengJun::getSn(1),
                'goods_count' => 0,
                'goods_amount' => 0,
                'discount_amount' => 0,
                'order_amount' => 0,
                'user_name' => '无',
                'user_mobile' => '无',
                'user_adds' => '无',
                'user_id' => $uid,
                'pay_status' => 0,
                'status' => 5,
                'type' => 9,
            ]);
            $ogModel = [];
            foreach ($params['goods'] as $k => $v) {
                $ogModel[$k]['order_id'] = $params['order_id'];
                $ogModel[$k]['goods_id'] = $v['goods_id'];
                $ogModel[$k]['goods_name'] = $v['goods_name'];
                $ogModel[$k]['product_img'] = $v['product_img'];
                $ogModel[$k]['goods_product_id'] = 0;
                $ogModel[$k]['product_price'] = 0;
                $ogModel[$k]['product_line_price'] = 0;
                $ogModel[$k]['product_name'] = '';
                $ogModel[$k]['quantity'] = 1;
            }
            (new OrderGoodsModel)->insertAll($ogModel);
        }
        $id = $params['id'];
        $model = [
            'user_id' => $uid,
            'content' => $params['content'],
            'type' => $params['type'],
            'order_id' => $params['order_id'],
            'circle_id' => $params['circle']['id'],
            'circle_name' => $params['circle']['name'],
            'circle_avatar' => $params['circle']['avatar'],
            'activity_id' => $params['activity']['id'],
            'activity_name' => $params['activity']['name'],
            'activity_img' => $params['activity']['img'],
        ];
        if (!empty($params['adds'])) {
            $model['adds'] = $params['adds']['address'];
            $model['adds_name'] = $params['adds']['name'];
            $model['lat'] = $params['adds']['latitude'];
            $model['lng'] = $params['adds']['longitude'];
        }
        if ($id) {
            $model['status'] = $params['status'] == 0 ? 0 : 1;
            $model['update_time'] = time();
            DynamicModel::where('id', $id)->update($model);
            if ($params['type'] == 1) DynamicImgModel::where('dynamic_id', $id)->delete();
            if ($params['type'] == 2) DynamicVideoModel::where('dynamic_id', $id)->delete();
            if ($params['type'] == 3) DynamicAudioModel::where('dynamic_id', $id)->delete();
        } else {
            $model['status'] = $params['status'];
            $model['create_time'] = time();
            $model = SuPengJun::ipStr($model, $request->ip()); // IP归属地
            $id = (new DynamicModel)->insertGetId($model);
            if ($params['order_id']) OrderModel::where('id', $params['order_id'])->update(['status' => 5]);
        }
        if ($params['type'] == 1 && !empty($params['imgs'])) {
            $img_model = [];
            foreach ($params['imgs'] as $k => $v) {
                $img_model[$k]['url'] = $v['url'];
                $img_model[$k]['wide'] = $v['wide'];
                $img_model[$k]['high'] = $v['high'];
                $img_model[$k]['dynamic_id'] = $id;
                $img_model[$k]['user_id'] = $uid;
            }
            (new DynamicImgModel)->insertAll($img_model);
        }
        if ($params['type'] == 2 && !empty($params['video'])) {
            (new DynamicVideoModel())->insert([
                'url' => $params['video']['url'],
                'cover' => $params['video']['cover'],
                'wide' => $params['video']['wide'],
                'high' => $params['video']['high'],
                'dynamic_id' => $id,
                'user_id' => $uid
            ]);
        }
        if ($params['type'] == 3 && !empty($params['audio'])) {
            (new DynamicAudioModel())->insert([
                'cover' => $params['audio']['cover'],
                'url' => $params['audio']['url'],
                'name' => $params['audio']['name'],
                'intro' => $params['audio']['intro'],
                'size' => $params['audio']['size'],
                'dynamic_id' => $id,
                'user_id' => $uid
            ]);
        }
        if ($params['circle']['id']) {
            (new Client())->push(CircleJob::class, $params['circle']);
        }
        event('DynamicAudit', ['did' => $id]);
        return success($params['status'] ? '发布成功 🎉' : '保存成功 🎉');
    }

    /**
     * 动态详情（未发现调用）
     * @param array $id 动态ID
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function info(Request $request)
    {
        $id = $request->get('id', 0);
        $data = DynamicModel::where('id', $id)->field(DynamicService::dynamic_find())->find();
        if ($data) {
            if ($data['type'] == 1) {
                $data->imgs = DynamicImgModel::where('dynamic_id', $id)
                    ->field('url,wide,high')
                    ->select();
            } else if ($data['type'] == 2) {
                $data->video = DynamicVideoModel::where('dynamic_id', $id)
                    ->field('url,cover,wide,high')
                    ->find();
            } else if ($data['type'] == 3) {
                $data->audio = DynamicAudioModel::where('dynamic_id', $id)
                    ->field('url,cover,name,intro,size')
                    ->find();
            }
            $data['order_type'] = 0;
            if ($data['order_id']) {
                $data['order_type'] = OrderModel::where('id', $data['order_id'])->value('type');
                $data->goods = OrderGoodsModel::where('order_id', $data['order_id'])
                    ->field('goods_id,goods_name,product_img')
                    ->select();
            }
        }
        return success('success', $data);
    }

    /**
     * 订单商品信息（未发现调用）
     * @param array $id 订单ID
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function order_goods(Request $request)
    {
        $id = $request->get('id', 0);
        $data = OrderGoodsModel::where('order_id', $id)
            ->field('goods_name,product_img')
            ->select();
        return success('success', $data);
    }

    /**
     * 获取推荐动态列表
     */
    public function recommend(Request $request)
    {
        $uid = $request->uid;
        $follow = $request->get('follow', 0);
        $adds = $request->get('adds', '');
        $type = $request->get('type', 0);
        $circleId = $request->get('circle_id', 0);
        $activityId = $request->get('activity_id', 0);
        $order = ['top' => 'desc', 'id' => 'desc', 'browse' => 'desc'];
        $condition[] = ['status', '=', 2];
        if ($type == 1) $order = ['id' => 'desc', 'browse' => 'desc'];
        if ($type == 2) $order = ['browse' => 'desc', 'id' => 'desc'];
        if ($circleId) $condition[] = ['circle_id', '=', $circleId];
        if ($activityId) $condition[] = ['activity_id', '=', $activityId];
        if ($adds) $condition[] = ['adds_name|adds|district|city|province|country', 'like', '%' . $adds . '%'];
        if ($follow == 1) $condition[] = ['user_id', 'in', UserFollowModel::where('user_id', $uid)->column('follow_id')];
        $data = DynamicModel::where($condition)->order($order)
            ->field(DynamicService::dynamic_find())
            ->paginate(8);
        $data = DynamicService::dynamic_map($data, $uid, 1);
        DynamicModel::whereIn('id', $data->column('id'))->update(['browse' => new \think\db\Raw('browse+1')]);
        return success('success', $data);
    }

    /**
     * 动态详情
     */
    public function details(Request $request)
    {
        $uid = $request->uid;
        $id = $request->get('id', 0);
        $data = DynamicModel::where('id', $id)->field(DynamicService::dynamic_find())->find();
        if (!$data) return error('笔记异常或已被删除，请稍后重试！', 600201);
        DynamicModel::where('id', $id)->update(['browse' => new \think\db\Raw('browse+1')]);
        $data['user'] = UserModel::where('id', $data['user_id'])->field('name,avatar,gender,age')->find();
        if ($data['type'] == 1) {
            $data['imgs'] = DynamicImgModel::where('dynamic_id', $data['id'])
                ->field('url,wide,high')
                ->select();
            $data['img_count'] = DynamicImgModel::where('dynamic_id', $data['id'])->count();
        } else if ($data['type'] == 2) {
            $data['video'] = DynamicVideoModel::where('dynamic_id', $data['id'])
                ->field('url,cover,wide,high')
                ->find();
        } else if ($data['type'] == 3) {
            $data['audio'] = DynamicAudioModel::where('dynamic_id', $data['id'])
                ->field('url,cover,name,intro')
                ->find();
        }
        if ($data['order_id']) {
            $data->goods = OrderGoodsModel::where('order_id', $data['order_id'])
                ->field('goods_id,goods_name,product_img')
                ->select();
        }
        $province = $data['province'];
        if (!$province) $province = $data['city'];
        if (!$province) $province = $data['country'];
        $data['province'] = SuPengJun::addsStr($province);
        $data['create_time_str'] = SuPengJun::timeStr($data['create_time']);
        $data['comment_count'] = DynamicCommentModel::where('dynamic_id', $data['id'])->count();
        $data['like_count'] = DynamicLikeModel::where('dynamic_id', $data['id'])->count() + $data['likes'];
        $data['like_count_str'] = SuPengJun::convert($data['like_count']);
        $data['is_like'] = DynamicLikeModel::where('dynamic_id', $data['id'])->where('user_id', $uid)->value('id') > 0;
        $data['is_follow'] = UserFollowModel::where('user_id', $uid)->where('follow_id', $data['user_id'])->value('id') > 0;
        $data['browse'] = SuPengJun::convert($data['browse']);
        return success('success', $data);
    }

    /**
     * 点赞
     */
    public function like(Request $request)
    {
        $uid = $request->uid;
        $id = $request->post('id');
        $dUid = $request->post('d_uid');
        $dImg = $request->post('d_img');
        $dContent = $request->post('d_content');
        $isLike = $request->post('is_like');
        if ($isLike) {
            (new DynamicLikeModel())->insert([
                'dynamic_id' => $id,
                'user_id' => $uid,
                'create_time' => time()
            ]);
            if ($uid != $dUid) {
                $avatarUrl = '/pages/user/details?id=' . $uid;
                $contentUrl = '/pages/note/details?id=' . $id;
                if ($dImg) {
                    $content = '<div style="margin-top: 4px;border-left: 4px solid #f5f5f5;padding-left: 8px;">
                    <img src="' . $dImg . '" style="width: 48px;height: 48px;border-radius: 4px;object-fit: cover;display: block;" /></div>';
                } else {
                    $content = '<p style="margin-top: 4px;color:#999;border-left: 4px solid #f5f5f5;padding-left: 8px;font-size: 11px;">' . SuPengJun::shorteStr($dContent) . '</p>';
                }
                (new NoticeModel())->send($dUid, '赞了你的笔记', $content, $uid, $avatarUrl, $contentUrl, 1);
            }
        } else {
            DynamicLikeModel::where('dynamic_id', $id)->where('user_id', $uid)->delete();
        }
        return success('success');
    }

    /**
     * 删除动态
     * @param array $id 动态ID
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function del(Request $request)
    {
        $id = $request->post('id', 0);
        DynamicLikeModel::where('dynamic_id', $id)->delete();
        DynamicModel::where('id', $id)->update(['status' => 5]);
        return success('已为您删除这篇笔记！');
    }

    /**
     * 举报动态
     * @param array $param 参数类型参数名参数作用
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function reason(Request $request)
    {
        $uid = $request->uid;
        $reason = $request->post('reason');
        $id = $request->post('id', 0);
        $dUid = $request->post('d_uid');
        $dImg = $request->post('d_img');
        $dContent = $request->post('d_content');
        if ($uid != $dUid) {
            $top = DynamicModel::where('id', $id)->value('top');
            if ($top == 1) return error('置顶笔记无法举报！');
            $type = UserModel::where('id', $dUid)->value('type');
            if ($type == 2) return error('官方笔记无法举报！');
            DynamicModel::where('id', $id)->update(['status' => 3]);
            $contentUrl = '/pages/note/details?id=' . $id;
            if ($dImg) {
                $content = '原因：' . $reason . '<br>建议修改后重新发布，否则无法获得更多曝光<br>' . '<div style="margin-top: 4px;border-left: 4px solid #f5f5f5;padding-left: 8px;">
                <img src="' . $dImg . '" style="width: 48px;height: 48px;border-radius: 4px;object-fit: cover;display: block;" /></div>';
            } else {
                $content = '原因：' . $reason . '<br>建议修改后重新发布，否则无法获得更多曝光<br><p style="margin-top: 8px;color:#999;border-left: 4px solid #f5f5f5;padding-left: 8px;font-size: 11px;">' . SuPengJun::shorteStr($dContent) . '</p>';
            }
            (new NoticeModel())->send($dUid, '笔记违规', $content, 0, '', $contentUrl, 1);
            event('ReasonDynamic', ['did' => $id, 'reason' => $reason]);
            return success('提交成功，感谢您的举报！');
        } else {
            return error('您不能举报您自己的笔记！');
        }
    }
}
